const upType = (type) => {
    const tab = document.getElementsByClassName('cj-tab')[0].getElementsByTagName("p")
    const content = document.getElementsByClassName('cj-box')
    switch (type) {
        case 1:
            tab[0].classList.add("cj-active");
            tab[1].classList.remove("cj-active");
            content[0].classList.add("cj-show")
            content[1].classList.add("cj-hide")
            content[0].classList.remove("cj-hide")
            content[1].classList.remove("cj-show")
            break;
        case 2:
            tab[0].classList.remove("cj-active");
            tab[1].classList.add("cj-active");
            content[0].classList.add("cj-hide")
            content[1].classList.add("cj-show")
            content[0].classList.remove("cj-show")
            content[1].classList.remove("cj-hide")
            break;
    }
}

const upPreview = (obj, ctrlid) => {
    const file = document.getElementById('cj-upload').value;//获取文件
    const index = file.lastIndexOf('.'); //获取最后一位小数点
    const extension = file.substr(index + 1);
    const arr = ["jpg", "gif", "png", "jpeg", "bmp", "webp"];
    if (arr.includes(extension)) {
        const bf = obj.files[0];
        upLoadFile(bf, ctrlid);
    } else {
        file.value = ''
        alert('仅支持jpg、gif、png、jpeg、bmp、webp后缀格式');
        return false;
    }
}

const upLoadFile = (fileObj, ctrlid) => {
    const button = document.getElementById(ctrlid + '_submit').getElementsByTagName('strong')[0]
    button.onclick = upRefuse
    button.innerText = '图片上传中'
    const form = new FormData(); // FormData 对象
    form.append("file", fileObj); // 文件对象
    xhr = new XMLHttpRequest();  // XMLHttpRequest 对象
    xhr.open("post", "https://img.isdalao.com", true); //post方式，url为服务器请求地址，true 该参数规定请求是否异步处理。
    xhr.send(form); //开始上传，发送form数据
    xhr.onreadystatechange = () => {
        let data = xhr.responseText;
        try {
            data = JSON.parse(data)
            if (data.status != 20000) {
                alert(data.errMsg)
            } else {
                document.getElementById(ctrlid + '_param_1').value = data.result
                button.onclick = null
                button.innerText = '提交'
            }
        } catch (error) {

        }

    }
}

const upRefuse = ($event) => {
    $event.preventDefault()
    alert('请等待图片上传完成')
}


setInterval(() => {
    seditor_menu = (seditorkey, tag) => {
        var sel = false;
        if (!isUndefined($(seditorkey + 'message').selectionStart)) {
            sel = $(seditorkey + 'message').selectionEnd - $(seditorkey + 'message').selectionStart;
        } else if (document.selection && document.selection.createRange) {
            $(seditorkey + 'message').focus();
            var sel = document.selection.createRange();
            $(seditorkey + 'message').sel = sel;
            sel = sel.text ? true : false;
        }
        if (sel) {
            seditor_insertunit(seditorkey, '[' + tag + ']', '[/' + tag + ']');
            return;
        }
        var ctrlid = seditorkey + tag;
        var menuid = ctrlid + '_menu';
        if (!$(menuid)) {
            switch (tag) {
                case 'at':
                    curatli = 0;
                    atsubmitid = ctrlid + '_submit';
                    setTimeout(function () {
                        atFilter('', 'at_list', 'atListSet');
                        $('atkeyword').focus();
                    }, 100);
                    str = '请输用户名:<br /><input type="text" id="atkeyword" style="width:240px" value="" class="px" onkeydown="atFilter(this.value, \'at_list\',\'atListSet\',event);" /><div class="p_pop" id="at_list" style="width:250px;"><ul><li>@朋友账号，就能提醒他来看帖子</li></ul></div>';
                    submitstr = 'seditor_insertunit(\'' + seditorkey + '\', \'@\' + $(\'atkeyword\').value.replace(/<\\/?b>/g, \'\')+\' \'); hideMenu();';
                    break;
                case 'url':
                    str = '请输入链接地址:<br /><input type="text" id="' + ctrlid + '_param_1" sautocomplete="off" style="width: 98%" value="" class="px" />' + '<br />请输入链接文字:<br /><input type="text" id="' + ctrlid + '_param_2" style="width: 98%" value="" class="px" />';
                    submitstr = "$('" + ctrlid + "_param_2').value !== '' ? seditor_insertunit('" + seditorkey + "', '[url='+seditor_squarestrip($('" + ctrlid + "_param_1').value)+']'+$('" + ctrlid + "_param_2').value, '[/url]', null, 1) : seditor_insertunit('" + seditorkey + "', '[url]'+$('" + ctrlid + "_param_1').value, '[/url]', null, 1);hideMenu();";
                    break;
                case 'code':
                case 'quote':
                    var tagl = {
                        'quote': '请输入要插入的引用',
                        'code': '请输入要插入的代码'
                    };
                    str = tagl[tag] + ':<br /><textarea id="' + ctrlid + '_param_1" style="width: 98%" cols="50" rows="5" class="txtarea"></textarea>';
                    submitstr = "seditor_insertunit('" + seditorkey + "', '[" + tag + "]'+$('" + ctrlid + "_param_1').value, '[/" + tag + "]', null, 1);hideMenu();";
                    break;
                case 'img':
                    str = `
                        <div class="wapj cj-tab">
                            <p onclick="upType(1)" class="cj-active">上传图片</p>
                            <p onclick="upType(2)">网络图片</p>
                        </div>
                        <div class="wapj cj-content">
                            <section >
                                <p class="cj-box cj-show">
                                    <input type="file" accept="image/*" id="cj-upload" onChange="upPreview(this,\'${ctrlid}\')"/>
                                </p>
                                <p class="cj-box cj-hide">
                                    <span>图片地址:</span>
                                    <input type="text" id="${ctrlid}_param_1" value="" onchange="loadimgsize(this.value, \''${seditorkey}'\',\''${tag}'\')" />
                                </p>
                                <div>
                                    <p>宽（可选）</p>
                                    <p>高（可选）</p>
                                </div>
                                <div>
                                    <p><input type="text" id="${ctrlid}_param_2" value=""></p>
                                    <p><input type="text" id="${ctrlid}_param_3" value=""></p>
                                </div>
                            </section>
                        </div>
                
                `
                    submitstr = "seditor_insertunit('" + seditorkey + "', '[img' + ($('" + ctrlid + "_param_2').value !== '' && $('" + ctrlid + "_param_3').value !== '' ? '='+$('" + ctrlid + "_param_2').value+','+$('" + ctrlid + "_param_3').value : '')+']'+seditor_squarestrip($('" + ctrlid + "_param_1').value), '[/img]', null, 1);hideMenu();";
                    break;
            }
            var menu = document.createElement('div');
            menu.id = menuid;
            menu.style.display = 'none';
            menu.className = 'p_pof upf';
            menu.style.width = '270px';
            $('append_parent').appendChild(menu);
            menu.innerHTML = '<span class="y"><a onclick="hideMenu()" class="flbc" href="javascript:;">关闭</a></span><div class="p_opt cl"><form onsubmit="' + submitstr + ';return false;" autocomplete="off"><div>' + str + '</div><div class="pns mtn"><button type="submit" id="' + ctrlid + '_submit" class="pn pnc"><strong>提交</strong></button><button type="button" onClick="hideMenu()" class="pn"><em>取消</em></button></div></form></div>';
        }
        showMenu({
            'ctrlid': ctrlid,
            'evt': 'click',
            'duration': 3,
            'cache': 0,
            'drag': 1
        });
    }
}, 1000);
